<template>
  <div class="imageUpload-container">
    <!-- on-preview 点击图片预览时的钩子
          on-remove 删除图片时的钩子
     -->
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :class="{ hidden: isHidden }"
      :http-request="upLoad"
      :on-change="handleChange"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress
      v-if="showPro"
      style="width:198px"
      :percentage="percent"
    ></el-progress>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
// 导入腾讯云sdk
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID3uUnqc7MJ0QZR2MPBguvmQuCH6gz0kFT',
  SecretKey: 'yg8JDqCI7sMZVChz1mGTP4SZQ0JL6bpm'
})
export default {
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      percent: 0,
      showPro: false
    }
  },
  computed: {
    isHidden () {
      return this.fileList.length > 0
    }
  },
  methods: {
    // 文件状态改变时的回调函数
    handleChange (file, fileList) {
      this.fileList = fileList
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
      this.fileList = []
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 自定义上传
    upLoad (params) {
      console.log(params)
      this.showPro = true
      cos.putObject(
        {
          Bucket: 'luoyu-1306481846' /* 必须 */, // 存储桶名称
          Region: 'ap-shenzhen-fsi' /* 存储桶所在地域，必须字段 */, // 存储桶所在地域
          Key: params.file.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: params.file, // 上传文件对象
          // 上传进度的回调函数
          onProgress: progressData => {
            console.log(progressData)
            this.percent = progressData.percent * 100
          }
        },
        (err, data) => {
          console.log(err || data)
          if (!err) {
            this.fileList = [{ url: 'http://' + data.Location }]
          }
          // this.percent = 0
          this.showPro = false
        }
      )
    }
  }
}
</script>

<style lang="scss">
.imageUpload-container {
  .hidden {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
